<?php


namespace PKFrame\Lib\Cache;
defined('PATH_PK') or die();

use PKFrame\DataHandler\JSON;

class Tmp
{

    private static $instance;

    /**
     * @return Tmp
     */
    public static function getInstance(): Tmp
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }

        return self::$instance;
    }

    public function Read(string $name_file, string $name_dir = null)
    {
        $content = fileHelper()->GetContentsByDisk(
            PATH_TMP . ucfirst($name_dir) . DS . strtolower($name_file)
        );
        if (empty($content)) {
            return null;
        }
        return $content;
    }

    public function ReadByJSON(string $name_file, string $name_dir = null): ?array
    {
        $content = $this->Read($name_file . '.json', $name_dir);
        if (empty($content)) {
            return [];
        }
        return json_decode($content, true);
    }

    public function Write(string $name_file, string $data, string $name_dir = null, bool $isTop = true)
    {
        fileHelper()->PutContents(PATH_TMP . ucfirst($name_dir), strtolower($name_file), $data, $isTop);
    }

    public function WriteByJSON(string $name_file, array $data, string $name_dir = null)
    {
        $this->Write($name_file . '.json', JSON::EnCode($data), $name_dir);
    }

    public function RemoveDir(string $name_dir)
    {
        fileHelper()->UnLink(PATH_TMP . ucfirst($name_dir));
    }

}